import { ref, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import type { RouteMenu, TabMenu } from '@/type/Menu'

// 定义 localStorage 键名常量
const STORAGE_KEYS = {
  DYNAMIC_MENU: 'dynamic_menu',
  TAB_MENU: 'tab_menu',
  CURRENT_MENU: 'current_menu'
}

// 初始化时读取 localStorage
const initialData = (() => {
  try {
    return {
      tab: JSON.parse(localStorage.getItem(STORAGE_KEYS.TAB_MENU) || '[]') as TabMenu[],
      currentMenu: localStorage.getItem(STORAGE_KEYS.CURRENT_MENU)
    }
  } catch (error) {
    console.error('LocalStorage 解析失败:', error)
    return {
      dynamic: [],
      tab: [],
      currentMenu: null
    }
  }
})()

export const useMenuStore = defineStore('menu', () => {
  // 状态初始化
  const dynamic = ref<RouteMenu[]>([])
  const tab = ref<TabMenu[]>(initialData.tab)
  const currentMenu = ref<string | null>(initialData.currentMenu)

  // 自动同步到 localStorage
  watchEffect(() => {
    localStorage.setItem(STORAGE_KEYS.TAB_MENU, JSON.stringify(tab.value))
    if (currentMenu.value) {
      localStorage.setItem(STORAGE_KEYS.CURRENT_MENU, currentMenu.value)
    } else {
      localStorage.removeItem(STORAGE_KEYS.CURRENT_MENU)
    }
  })

  // 操作函数
  function setDynamic(d: RouteMenu[]) {
    dynamic.value = d
  }

  function setCurrentMenu(m: string | null) {
    currentMenu.value = m
  }

  function setTab(t: TabMenu) {
    const existingTab = tab.value.find(it => it.innerId === t.innerId)
    if (!existingTab) {
      tab.value.push(t)
      return
    }

    // 更新现有选项卡
    Object.assign(existingTab, t)
  }

  function closeTab(innerId: string) {
    tab.value = tab.value.filter((it) => it.innerId !== innerId)
  }

  function closeTabOfPath(path: string) {
    tab.value = tab.value.filter((it) => {
      if (it.path === path && it.innerId === currentMenu.value) {
        currentMenu.value = null
      }
      return it.path !== path
    })
  }

  // 重新排序标签页
  function reorderTabs(newOrder: TabMenu[]) {
    tab.value = newOrder
  }

  // 重置菜单状态（可选）
  function resetMenu() {
    dynamic.value = []
    tab.value = []
    currentMenu.value = null
  }

  return {
    dynamic,
    currentMenu,
    tab,
    setDynamic,
    setCurrentMenu,
    setTab,
    closeTab,
    closeTabOfPath,
    reorderTabs,
    resetMenu
  }
})
